<template>
    <div class="container">
        <a-card title="产品管理">
            <div style="padding: 20px">
                <h2>物料/产品添加顺序</h2>
                <a-steps progress-dot :current="5">
                    <a-step title="添加物料：中药材" sub-title="步骤一"/>
                    <a-step title="添加物料：半成品提取饮片" sub-title="步骤二"/>
                    <a-step title="添加物料：半成品提取物" sub-title="步骤三"/>
                    <a-step title="添加物料：待包装成品颗粒" sub-title="步骤四"/>
                    <a-step title="添加物料：成品颗粒" sub-title="步骤五"/>
                </a-steps>
            </div>
            <div class="tool-bar">
                <div style="display: flex; gap: 10px;">
                    <a-input-search allowClear v-model="searchParams.name" placeholder="请输入品名" @search="search" style="width: 180px;" />
                    <a-select v-model="searchParams.standard" allowClear placeholder="请选择标准" style="width: 140px;" @change="search">
                        <a-select-option value="国标">国标</a-select-option>
                        <a-select-option value="省标">省标</a-select-option>
                        <a-select-option value="省标-北京">省标-北京</a-select-option>
                        <a-select-option value="省标-上海">省标-上海</a-select-option>
                    </a-select>
                    <a-select v-if="curTab === 0" v-model="searchParams.inventoryType" allowClear placeholder="请选择产品大类" style="width: 140px;" @change="search">
                        <a-select-option value="C60">C60</a-select-option>
                        <a-select-option value="C70">C70</a-select-option>
                        <a-select-option value="C80">C80</a-select-option>
                        <a-select-option value="C90">C90</a-select-option>
                        <a-select-option value="C81">C81</a-select-option>
                        <a-select-option value="C91">C91</a-select-option>
                        <a-select-option value="C82">C82</a-select-option>
                        <a-select-option value="C92">C92</a-select-option>
                    </a-select>
                </div>
                <a-row>
                    <a-col :span="24">
                        <a-button type="primary" @click="exportQuarterSellTemplate">导出维护信息模板</a-button>
                        <a-upload
                            name="file"
                            :showUploadList="false"
                            :beforeUpload="beforeQuarterUpload"
                            accept=".xls,.xlsx"
                            style="display:inline-block;margin-right:10px;"
                        >
                            <a-button type="primary">导入维护信息</a-button>
                        </a-upload>
                        <a-button id="新增" type="primary" @click="add">新增</a-button>
                        <a-button type="primary" @click="downLoadTemplate">下载导入模板</a-button>
                        
                        <a-upload name="file" :multiple="false" :showUploadList="false" :beforeUpload="beforeUpload">
                            <a-button type="primary">导入</a-button>
                        </a-upload>
                    </a-col>
                </a-row>
            </div>
            <a-tabs type="card" :activeKey="curTab" :default-active-key="0" @change="tabsChange">
                <a-tab-pane v-for="(item,i) in tab1" :key="i" :tab="item">
                    <div class="table">
                        <a-table :loading="tabTableOption.loading" bordered :columns="tabTableOption.columns" :data-source="tabTableOption.dataSource" :pagination="tabTableOption.pagination">
                        <span slot="action" slot-scope="text, record">
                            <a-button size="small" class="actionBtn" type="primary" @click="edit(record)">编辑</a-button>
                            <a-button size="small" class="actionBtn" type="primary" @click="detail(record)">详情</a-button>
                            <a-button size="small" class="actionBtn" :type="record.state?'danger':'primary'" @click="clickDisable(record)">{{record.state?'禁用':'启用'}}</a-button>
                            <!--                            <a-popconfirm okText="确定" cancelText="取消" title="确定删除吗？" @confirm="deleteProduct(record)">-->
<!--                                <a-button size="small" class="actionBtn" type="danger">删除</a-button>-->
<!--                            </a-popconfirm>-->
                        </span>
                        </a-table>
                    </div>
                </a-tab-pane>
                <a-tab-pane id="半成品" :key="2" tab="半成品">
                    <a-tabs type="card" :activeKey="curTab2" :default-active-key="0" @change="tabsChange2">
                        <a-tab-pane v-for="(item,i) in tab2" :key="i" :tab="item">
                            <div class="table">
                                <a-table :loading="tabTableOption.loading" bordered :columns="tabTableOption.columns" :data-source="tabTableOption.dataSource" :pagination="tabTableOption.pagination">
                                    <span slot="action" slot-scope="text, record">
                                        <a-button size="small" class="actionBtn" type="primary" @click="edit(record)">编辑</a-button>
                                        <a-button size="small" class="actionBtn" type="primary" @click="detail(record)">详情</a-button>
                                        <a-button size="small" class="actionBtn" :type="record.state?'danger':'primary'" @click="clickDisable(record)">{{record.state?'禁用':'启用'}}</a-button>
                                        <!--                            <a-popconfirm okText="确定" cancelText="取消" title="确定删除吗？" @confirm="deleteProduct(record)">-->
            <!--                                <a-button size="small" class="actionBtn" type="danger">删除</a-button>-->
            <!--                            </a-popconfirm>-->
                                    </span>
                                </a-table>
                            </div>
                        </a-tab-pane>
                    </a-tabs>
                </a-tab-pane>
            </a-tabs>
        </a-card>
        <add-or-edit :type="tab1[curTab]" :material-type="tab2[curTab2]" :viewDetail="viewDetail" :editId="editId" :visible="modalVisible" @closeModal="onClose"/>
    </div>
</template>
<script lang="ts">
import {Vue, Component} from 'vue-property-decorator';
import addOrEdit from "@/views/settingView/productMgt/components/addOrEdit.vue";
import nextApi from "@/api/nextApi";
import {h} from "vue";
import { driver } from "driver.js";
import "driver.js/dist/driver.css";
import {downLoadFile} from "@/utils";
@Component({
    name: 'productManage',
    components: {addOrEdit}
})
export default class extends Vue {

    //tabs配置
    tab1:string[] = ['成品','待包装成品']
    tab2:string[] = ['提取物','提取饮片']
    //成品表格配置
    columns :any =  [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            width: 80,
            align: 'center',
            customRender: (text: string, record: any, index: number) => `${index + 1}`,
        },
        {
            title: '产品名称',
            dataIndex: 'name',
            key: 'name',
            align: 'center',
        },
        {
            title: '标准',
            dataIndex: 'standard',
            key: 'standard',
            align: 'center',
        },
        {
            title: '产品代码',
            dataIndex: 'code',
            key: 'code',
            align: 'center',
        },
        {
            title: '状态',
            dataIndex: 'state',
            key: 'state',
            align: 'center',
            customRender: (text: string, record: any, index: number) => {
                const stateBox = h(
                    "div",
                    { class: record.state === true ? "c-success" : "c-danger" },
                    record.state === true ? "启用" : "禁用"
                );
                return stateBox;
            },
        },
        {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            align: 'center',
            width: 280,
            scopedSlots: { customRender: 'action' },
        }
    ]
    // 待包装成品/半成品表格配置
    tabTableOption: any = {
        loading:false,
        columns: [],
        dataSource: [],
        pagination: {
            pageSize: 10,
            current: 1,
            total: 0,
            showTotal: (total: number | string) => `共${total}条`,
            onChange: this.pageChange,
        },
    }

    searchParams = {
        name: "",
        standard: undefined,
        inventoryType: undefined,
    }
    search() {
        this.tabsChange(this.curTab);
    }

    /**
     * @description 处理数据和逻辑
     * **/
    curTab = 0
    tabsChange(key){
        this.tabTableOption.columns = [...this.columns];
        this.curTab = key
        if(key == 0){
            //给表格配置插入产品大类列
            this.tabTableOption.columns.splice(2,0,{
                title: '产品大类',
                dataIndex: 'inventoryType',
                key: 'inventoryType',
                align: 'center',
            })
        }
        //切换tab查询数据
        let realTabData:string[] = ['成品','待包装成品','半成品']
        if(key === 2){
            this.tabsChange2(this.curTab2)
        }else{
            this.getTableData(realTabData[key])
        }
    }
    curTab2 = 0
    tabsChange2(key:number){
        console.log('半成品二级tab索引：',key)
        this.curTab2 = key
        let materialType = this.tab2[key]
        this.getTableData('半成品',materialType)
    }
    downLoadTemplate(){
        this.tabTableOption.loading = true;
        nextApi.downloadMaterialTpl({ materialType: this.getTabName()}, (res: any) => {
            const blob = new Blob([res.data], {
                //type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                type: "application/vnd.ms-excel",
            });
            downLoadFile(blob, this.getTabName() + "_导入模板");
            this.tabTableOption.loading = false;
        });
    }
    getTabName(){
        switch (this.curTab) {
            case 0:
                return '配方颗粒'
            case 1:
                return '配方颗粒(颗粒)'
            case 2:
                switch (this.curTab2) {
                    case 0:
                        return '提取物'
                    case 1:
                        return '饮片'
                    default:
                        return '提取物'
                }
        }
    }
    beforeUpload(file) {
        let materialType:any = this.getTabName()
        let formData = new FormData();
        formData.append("file", file);
        formData.append("materialType", materialType);
        //do something
        this.uploadAccount(formData);
        return false;
    }
    async uploadAccount(formData: any) {
        this.tabTableOption.loading = true;
        try {
            const res = await nextApi.importMPData(formData);
            console.log(res)
            this.$message.success(res.msg);
            this.tabsChange(this.curTab)
        } finally {
            this.tabTableOption.loading = false;
        }
    }
    modalVisible = false
    add(){
        this.modalVisible = true
    }
    editId = ''
    edit(record){
        this.editId = record.id
        this.modalVisible = true
    }
    async deleteProduct(record){
        const res = await nextApi.deleteRecord({id:record.id})
        if(res.code === 200){
            this.$message.success(res.msg)
            this.tabsChange(this.curTab)
        }
    }
    viewDetail = false
    detail(record){
        this.editId = record.id
        this.viewDetail = true
        this.modalVisible = true
    }
    async clickDisable(item:any){
        try{
            this.tabTableOption.loading = true
            let {state,id} = item
            const res = await nextApi.changeState({id,state:!state})
            this.$message.success(res.msg)
        }finally {
            this.tabTableOption.loading = false
            await this.tabsChange(this.curTab)
        }

    }
    onClose(){
        this.modalVisible = false;
        this.viewDetail = false
        this.editId = "";
        this.tabsChange(this.curTab)
    }
    type
    materialType
    pageChange(page: number, pageSize: number){
        console.log(page)
        this.tabTableOption.pagination.current = page
        this.getTableData(this.type,this.materialType)
    }

    /**
     * @description 请求接口
     * **/
    async getTableData(type?,materialType?){
        try{
            this.type = type
            this.materialType = materialType
            this.materialType = this.materialType == '提取饮片' ? '饮片':this.materialType
            this.materialType = this.materialType == '提取物' ? '提取物':this.materialType
            this.tabTableOption.loading = true
            let params = {
                page:this.tabTableOption.pagination.current,
                pageSize:this.tabTableOption.pagination.pageSize,
                type,
                materialType:this.materialType,
                name:this.searchParams.name,
                standard:this.searchParams.standard,
                inventoryType:this.searchParams.inventoryType
            }
            const res = await nextApi.getMaterialList(params)
            this.tabTableOption.pagination.total = res.data?.total || 0
            this.tabTableOption.dataSource = res.data?.records || []
        }finally {
            this.tabTableOption.loading = false
        }
    }


    driver:any = null
    steps:any = [
        {
            element: "#半成品",
            popover: {
                title: "物料/产品添加顺序-步骤四",
                description: "添加半成品-提取饮片",
                side: "right",
                nextBtnText: "下一步",
                prevBtnText: "上一步",
            },
        },
        {
            element: "#新增",
            popover: {
                title: "物料/产品添加顺序-步骤五",
                description: "点击新增按钮填写所需要的数据",
                side: "right",
                nextBtnText: "下一步",
                prevBtnText: "上一步",
                onNextClick: () => {
                    this.curTab2 = 0
                    this.tabsChange2(this.curTab2)
                    this.moveNext()
                },
                onPrevClick: () => {
                    this.curTab = 2
                    this.tabsChange(this.curTab)
                    this.movePev()
                },
            },
        },
        {
            element: ".ant-tabs-tabpane-active",
            popover: {
                title: "物料/产品添加顺序-步骤六",
                description: "添加半成品-提取物",
                side: "right",
                nextBtnText: "下一步",
                prevBtnText: "上一步",
                onNextClick: () => {
                    this.curTab = 1
                    this.tabsChange(this.curTab)
                    this.moveNext()
                },
                onPrevClick: () => {
                    this.curTab2 = 1
                    this.tabsChange2(this.curTab2)
                    setTimeout(()=>{
                        this.movePev()

                    },200)
                },
            },
        },
        {
            element: ".ant-tabs-tab-active",
            popover: {
                title: "物料/产品添加顺序-步骤七",
                description: "添加待包装成品-配方颗粒(颗粒)",
                side: "right",
                nextBtnText: "下一步",
                prevBtnText: "上一步",
                onPrevClick: () => {
                    this.curTab = 2
                    this.tabsChange(this.curTab)
                    setTimeout(()=>{
                        this.movePev()
                    },200)
                },
            }
        },
        {
            element: "#新增",
            popover: {
                title: "物料/产品添加顺序-步骤八",
                description: "点击新增按钮填写配方颗粒(颗粒)所需要的数据",
                side: "right",
                nextBtnText: "我知道了",
                prevBtnText: "上一步",
                onNextClick: () => {
                    //销毁
                    this.driverDestroy()
                },
            }
        },
    ]
    startStep(){
        this.curTab = 2
        this.curTab2 = 1
        let tabClass = document.getElementsByClassName("ant-tabs-tab")
        this.driver = driver({
            showButtons: ["next", "previous", "close"],// 是否显示按钮
            showProgress: false, // 是否显示步骤进度
            steps: this.steps, // 步骤列表
            allowClose: true, // 是否点击蒙层进行关闭
        });
        this.driver.drive()
    }
    moveNext(){
        setTimeout(()=>{
            this.driver.moveNext()
        },400)
    }
    movePev(){
        setTimeout(()=>{
            this.driver.movePrevious()
        },400)
    }
    driverDestroy(){
        this.driver.destroy()
        localStorage.setItem("driver-enabled", 'false')
    }
    mounted() {
        const driverEnabled = localStorage.getItem("driver-enabled");
        let status = false;

        if (driverEnabled !== null) {
            try {
                status = JSON.parse(driverEnabled);
            } catch (error) {
                console.error("Error parsing driver-enabled from localStorage:", error);
                status = false; // 如果解析失败，默认设置为 false
            }
        }
        if(status){
            const fromMaterialPage = localStorage.getItem("fromMaterialPage");
            let fromStatus = false;
            if (fromMaterialPage !== null) {
                try {
                    fromStatus = JSON.parse(fromMaterialPage);
                } catch (error) {
                    console.error("Error parsing fromMaterialPage from localStorage:", error);
                    fromStatus = false; // 如果解析失败，默认设置为 false
                }
            }
            if (fromStatus) {
                this.startStep()
                this.curTab = 2
                this.tabsChange(this.curTab)
            }else{
                this.tabsChange(0)
            }
        }else{
            this.tabsChange(0)
        }
    }
    beforeQuarterUpload(file) {
        const formData = new FormData();
        formData.append('file', file);
        this.tabTableOption.loading = true;
        nextApi.importQuarterSell(formData).then(res => {
            this.$message.success(res.msg || '导入成功');
            this.tabsChange(this.curTab);
        }).catch(() => {
            this.$message.error('导入失败');
        }).finally(() => {
            this.tabTableOption.loading = false;
        });
        return false;
    }
    exportQuarterSellTemplate() {
        this.tabTableOption.loading = true;
        nextApi.exportQuarterSellEditTemplate((res: any) => {
            const blob = new Blob([res.data], {
                type: 'application/vnd.ms-excel',
            });
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', '季度销售模板.xls');
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
            this.tabTableOption.loading = false;
        });
    }
}
</script>
<style scoped lang="scss">
.container {
    padding: 20px;
    .tool-bar {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin: 10px 0;
        span {
            padding-left: 10px;
            font-size: 18px;
        }
        button {
            margin-left: 10px;
        }
    }
    .table {
        margin-top: 20px;
        .actionBtn{
            margin-right: 10px;
        }
    }
}
</style>
